package com.atguigu.exam.service.impl;

import com.atguigu.exam.config.properties.MinioProperties;
import com.atguigu.exam.service.FileUploadService;
import io.minio.*;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * projectName: com.atguigu.exam.service.impl
 *
 * @author: 赵伟风
 * description:
 */
@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private MinioProperties minioProperties;
    @Autowired
    private MinioClient minioClient;

    /**
     * 实现图片以及视频等文件的通用上传服务
     *
     * @param file
     * @param folder
     * @return
     */
    @Override
    public String uploadFile(MultipartFile file, String folder) throws Exception {
        //1.检查桶是否存在
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(minioProperties.getBucketName()).build());

        //2.不存在则创建桶
        if (!exists) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            String config = """
                        {
                              "Statement" : [ {
                                "Action" : "s3:GetObject",
                                "Effect" : "Allow",
                                "Principal" : "*",
                                "Resource" : "arn:aws:s3:::%s/*"
                              } ],
                              "Version" : "2012-10-17"
                        }
                    """.formatted(minioProperties.getBucketName());
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName())
                    .config(config).build());
        }
        //3.文件名称信息配置（分文件夹以及防止文件覆盖）
        String ObjectName = folder + "/" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/"
                + UUID.randomUUID().toString().replaceAll("-", "") + "_" + file.getOriginalFilename();
        log.info("文件上传服务中处理后的文件名为:{}", ObjectName);
        //4.upload上传文件
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .contentType(file.getContentType())
                .object(ObjectName)
                //partSize -1表示用minio默认规则切割文件
                .stream(file.getInputStream(), file.getSize(), -1)
                .build());

        //5.拼接url并且返回
        String url = String.join("/", minioProperties.getEndpoint(), minioProperties.getBucketName(), ObjectName);
        log.info("minio上传文件成功，返回的url为：{}", url);
        return url;
    }
}
